import wx
import time
import os

from test_panel_temp import MyPanel

Version = "0.1"
ReleaseDate = "2025-01-01"

cwd = os.getcwd()  # 获取当期程序所在的路径
print(f"cwd: {cwd}")

ID_EXIT = 200
ID_ABOUT = 201
ID_CALC = 300


class MainFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, size=(310, 450))
        self.img_path = None  # 工具图标路径
        self.status_bar = None  # 状态栏
        self.timer = None  # 状态栏的定时器
        self.panel = None  # 面板

        # 状态栏的创建
        self.setup_status_bar()
        # 菜单栏的创建
        self.setup_menu_bar()
        # 显示按钮功能
        self.init_ui()
        # 工具图标的实现
        self.setup_icon()

    def setup_status_bar(self):
        self.status_bar = self.CreateStatusBar(2)
        self.status_bar.SetStatusWidths([-1, -1])  # 状态栏[0]:状态栏[1]的比例 ==> 1:2
        self.status_bar.SetStatusText("Ready", 0)  # 设置状态栏[0]文本
        # Timer
        self.timer = wx.PyTimer(self.Notify)
        self.timer.Start(1000, wx.TIMER_CONTINUOUS)  # wx.TIMER_CONTINUOUS: 一直跑
        self.Notify()

    def setup_menu_bar(self):
        # *******************主菜单_start**************************
        menubar = wx.MenuBar()
        # 子菜单：退出（Quit），将子菜单添加到File中
        menu_file = wx.Menu()
        menu_quit = wx.MenuItem(menu_file, ID_EXIT, "退出(Q)", "Quit application")
        menu_quit.SetBitmap(wx.Bitmap("icons/quit.png"))
        menu_file.Append(menu_quit)
        menubar.Append(menu_file, "文件(F)")
        # 子菜单：关于（About），将子菜单添加到Help中
        menu_help = wx.Menu()
        menu_about = wx.MenuItem(menu_help, ID_ABOUT, "关于(A)", "About application")
        menu_about.SetBitmap(wx.Bitmap("icons/about.png"))
        menu_help.Append(menu_about)
        menubar.Append(menu_help, "帮助(H)")

        self.SetMenuBar(menubar)
        # *******************主菜单_end**************************

        # 菜单中子菜单，事件行为的绑定即实现
        self.Bind(wx.EVT_MENU, self.OnMenuExit, id=ID_EXIT)
        self.Bind(wx.EVT_MENU, self.OnMenuAbout, id=ID_ABOUT)
        self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)

    def init_ui(self):
        # 面板的显示
        self.panel = MyPanel(self, -1)
        global ID_CALC  # 定义 全局变量
        self.panel.result_str = ''  # 定义存储在文本中的变量

        # 放置可控文本
        self.panel.calc_result = wx.TextCtrl(self.panel, -1, '', pos=(20, 10), size=(250, 50), style=wx.TE_MULTILINE|wx.TE_RICH2)  # 多行文本和富文本格式
        font = wx.Font(18, wx.ROMAN, wx.NORMAL, wx.BOLD, underline=False)
        self.panel.calc_result.SetFont(font)

        vbox = wx.BoxSizer(wx.VERTICAL)
        # vbox.Add(self.panel.calc_result, 0, wx.ALL|wx.EXPAND|wx.ALIGN_CENTER_HORIZONTAL, 20)
        vbox.Add(self.panel.calc_result, 0, wx.ALL|wx.EXPAND, 20)

        # 放置按钮
        button_list = ['7', '8', '9', 'DEL', 'AC', '4', '5', '6', '*', '/', '1', '2', '3', '+',
                       '-', '0', '%', 'PI', 'e', 'sqrt', '^', 'sin', 'cos', 'tan', 'log', 'ln',
                       '(', ')', '·', '=']
        buttons = []
        for i, button in enumerate(button_list):
            buttons.append((wx.Button(self.panel, ID_CALC, label = "{}".format(button), size=(50, 40)), 0, wx.EXPAND))
            self.Bind(wx.EVT_BUTTON, self.panel.OnCalcClick, id=ID_CALC)
            ID_CALC += 1

        gs = wx.GridSizer(6, 5, 5, 5)  # 6rows, 5columns
        gs.AddMany(buttons)

        # vbox.Add(gs, 0, wx.ALL|wx.EXPAND|wx.ALIGN_CENTER_HORIZONTAL, 20)
        vbox.Add(gs, 0, wx.ALL|wx.EXPAND, 20)
        self.panel.SetSizer(vbox)

    def setup_icon(self):
        # 图标的实现
        self.img_path = os.path.abspath(cwd + "\\icons\\calculator.png")  # \--转义符
        # self.img_path = os.path.abspath("icons/calculator.png")
        icon = wx.Icon(self.img_path, type=wx.BITMAP_TYPE_PNG)
        self.SetIcon(icon)


    def Notify(self):
        time_local = time.localtime(time.time())
        strf_time_local = time.strftime("%Y-%m-%d %H:%M:%S", time_local)
        self.status_bar.SetStatusText(strf_time_local, 1)

    def OnMenuExit(self, event):
        self.Close()

    def OnMenuAbout(self, event):
        dlg = AboutDialog(None, -1)
        dlg.ShowModal()
        dlg.Destroy()

    def OnCloseWindow(self, event):
        self.Destroy()


class AboutDialog(wx.Dialog):
    def __init__(self, parent, id):
        wx.Dialog.__init__(self, parent, id, "About me", size=(200, 200))
        self.InitUI()

    def InitUI(self):
        vbox = wx.BoxSizer(wx.VERTICAL)  # 垂直--自上而下
        vbox.Add(wx.StaticText(self, -1, "Hello, I'm wxPython"),
                 0, wx.ALIGN_CENTER_HORIZONTAL | wx.Top, border=20)
        vbox.Add(wx.StaticText(self, -1, "(C) 2025 HAHA工作室)"),
                 0, wx.ALIGN_CENTER_HORIZONTAL | wx.Top, border=10)
        vbox.Add(wx.StaticText(self, -1, f"Version {Version}, {ReleaseDate}"),
                 0, wx.ALIGN_CENTER_HORIZONTAL | wx.Top, border=10)
        vbox.Add(wx.StaticText(self, -1, "Author : HAHA"),
                 0, wx.ALIGN_CENTER_HORIZONTAL | wx.Top, border=10)
        vbox.Add(wx.Button(self, wx.ID_OK), 0, wx.ALIGN_CENTER_HORIZONTAL | wx.BOTTOM, border=20)
        self.SetSizer(vbox)


class App(wx.App):
    def __init__(self):
        super(self.__class__, self).__init__()
        # wx.App.__init__(self)
        self.title = None
        self.version = None

    def OnInit(self):
        self.version = "lesson_9：简易计算器——图标icon、布局管理（wx.BoxSizer & wx.GridSizer）"
        self.title = "wxPython初级教程之" + self.version
        self.frame = MainFrame(None, -1, self.title)
        self.frame.Show(True)

        return True


if __name__ == "__main__":
    app = App()
    app.MainLoop()  # 启动主事件循环后，持续检查是否有事件需要处理，处理事件并更新界面，直到应用程序关闭。
